import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './entities/user.entity';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User) // 确保这里注入了 User 实体的 Repository
    private userRepository: Repository<User>,
  ) { }

  // 注册
  async create(createUserDto: CreateUserDto): Promise<User> {
    const { username } = createUserDto;
    // 判断用户是否存在
    const user = await this.userRepository.findOne({ where: { username } });
    if (user) {
      throw new HttpException('用户名已存在', HttpStatus.BAD_REQUEST)
    }
    const newUser = this.userRepository.create(createUserDto)
    return await this.userRepository.save(newUser);
  }

  // 获取所有用户
  async findAll() {
    return await this.userRepository.find({ where: { isDelete: 0 } })
  }

  // 获取单个用户
  async findOne(id: number) {
    const user = await this.userRepository.findOne({ where: { id, isDelete: 0 } });
    if (!user) {
      throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
    }
    return user;
  }

  // 更新用户信息
  async update(id: number, updateUserDto: UpdateUserDto): Promise<User> {
    const user = await this.userRepository.findOne({ where: { id, isDelete: 0 } });
    if (!user) {
      throw new HttpException('用户不存在或已删除', HttpStatus.NOT_FOUND);
    }
    // 更新用户数据
    const updatedUser = this.userRepository.merge(user, updateUserDto);
    return await this.userRepository.save(updatedUser);
  }

  // 移除用户
  async remove(id: number): Promise<string> {
    const user = await this.userRepository.findOne({ where: { id, isDelete: 0 } });
    if (!user) {
      throw new HttpException('用户不存在或已删除', HttpStatus.NOT_FOUND);
    }
    await this.userRepository.update(id, { isDelete: 1 });
    return `用户 ${id} 已被删除`;
  }

  // 恢复用户
  async restore(id: number): Promise<string> {
    const user = await this.userRepository.findOne({ where: { id, isDelete: 1 } });
    if (!user) {
      throw new HttpException('用户未被删除或不存在', HttpStatus.NOT_FOUND);
    }
    await this.userRepository.update(id, { isDelete: 0 });
    return `用户 ${id} 已被恢复`;
  }
}
